package com.exsun.gateway.jt809.common;

import com.exsun.gateway.jt809.config.Jt809Config;
import com.google.common.reflect.TypeToken;
import exsun.jt808.data.config.jt809.DevConfig;
import exsun.jt808.data.config.jt809.WebResponse;
import exsun.jt808.data.jt809_data.BasicVehicleInfo;
import exsun.jt808.data.util.FileUtil;
import exsun.jt808.data.util.GsonUtils;
import exsun.jt808.data.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class DevInfoService {
    private Logger logger = LoggerFactory.getLogger(DevInfoService.class);
    @Autowired
    private Jt809Config jt809Config;

    public static ConcurrentHashMap<String, BasicVehicleInfo> basicVehicleInfoDictionary;

//    @Autowired
//    private static BaseVehicleInfoService baseVehicleInfoService;

    String fileName = "DevConfig.txt";
    private void load(){
        basicVehicleInfoDictionary= new ConcurrentHashMap<String, BasicVehicleInfo>();
        String path = getPath().replace("file:", "")+ "/" + fileName;
        if(!FileUtil.isExist(path)){
            path = getPath().replace("target/classes/", "");
        }
        List<String> lines = FileUtil.readFileByLines(path);
        lines.forEach(line->{
            String[] info = line.split(";");
            BasicVehicleInfo basicVehicleInfo = new BasicVehicleInfo();
            basicVehicleInfo.setVehicleNo(info[0]);
            basicVehicleInfo.setVehicleColor(Integer.parseInt(info[2]));
            basicVehicleInfoDictionary.put(info[1], basicVehicleInfo);
        });
        logger.info("加载车辆数据"+basicVehicleInfoDictionary.size()+"条,路径:{}",path);
    }

    @Scheduled(cron = "${Scheduled.GetRegisteredVehiclesTimer}")
    private void loadVehicleInfo(){
        String str = HttpUtil.get(jt809Config.getHttpGetUrl()+"/equipmentManagement/vehicleDeviceColorList","",3000,3000,"UTF-8");
        Type type = new TypeToken<WebResponse<List<DevConfig>>>(){}.getType();
        WebResponse<List<DevConfig>> obj  = GsonUtils.getObjectFromJson(str,type);
        List<DevConfig> list = obj.data;
        list.forEach(line->{
                DevConfig devConfig = new DevConfig();
                devConfig.setNumberPlate(line.getNumberPlate());
                devConfig.setPlateColor(line.getPlateColor());
                devConfig.setDeviceId(line.getDeviceId());
                BasicVehicleInfo basicVehicleInfo = new BasicVehicleInfo();
                basicVehicleInfo.setVehicleNo(devConfig.getNumberPlate());
                basicVehicleInfo.setVehicleColor(devConfig.getPlateColor());
                basicVehicleInfoDictionary.put(devConfig.getDeviceId(),basicVehicleInfo);
        });
        logger.info("加载车辆数据"+basicVehicleInfoDictionary.size()+"条,路径:{}",jt809Config.getHttpGetUrl()+"/equipmentManagement/vehicleDeviceColorList");
    }

    public BasicVehicleInfo getBasicVehicleInfoByFile(String phoneNum){
        if(basicVehicleInfoDictionary == null){
            load();
        }
        if(basicVehicleInfoDictionary!=null&&basicVehicleInfoDictionary.containsKey(phoneNum)){
            return basicVehicleInfoDictionary.get(phoneNum);
        }
        return null;
    }

    public String getDevNoByVehNoByFile(String vehNo){
        if(basicVehicleInfoDictionary == null){
            load();
        }
        for (String key:basicVehicleInfoDictionary.keySet()) {
            if(basicVehicleInfoDictionary.get(key).getVehicleNo().equals(vehNo.trim())){
                System.out.println(vehNo.trim());
                return key;
            }
        }
        return null;
    }

    public boolean bSendTo809(String phoneNum){
        BasicVehicleInfo data =  getBasicVehicleInfoByFile(phoneNum);
        if(data == null)return false;
        return true;
    }

    public BasicVehicleInfo getBasicVehicleInfo(String phoneNum){
//        Map<String, Object> vehicleInfoByDevNo =
//                baseVehicleInfoService.queryVehicleInfoByDevNo(dvo);
//        BasicVehicleInfo basicVehicleInfo = new BasicVehicleInfo();
//        basicVehicleInfo.setVehicleNo(vehicleInfoByDevNo.get("vehicleNo").toString());
//        basicVehicleInfo.setVehicleColor(Integer.parseInt(vehicleInfoByDevNo.get("vehiclePlateColor").toString()));
//        return basicVehicleInfo;
        return getBasicVehicleInfoByFile(phoneNum);
    }
    /**
     * 通过车牌号获得设备号
     *
     * @param basicVehicleInfo
     * @return
     */
    public String getDevNoByVehNo(BasicVehicleInfo basicVehicleInfo) {
        //return baseVehicleInfoService.queryOneByVehNo(basicVehicleInfo.getVehicleNo()).getVehNo();
        return  getDevNoByVehNoByFile(basicVehicleInfo.getVehicleNo());
    }

    public String getPath()
    {
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if(System.getProperty("os.name").contains("dows"))
        {
            path = path.substring(1,path.length());
        }
        if(path.contains("jar"))
        {
            path = path.substring(0,path.lastIndexOf("."));
            return path.substring(0,path.lastIndexOf("/"));
        }
//        return path.replace("target/classes/", "");
        return path;
    }


}
